package cn.dakaqi.open.maibao;

import cn.dakaqi.annotation.EncryptionParam;
import cn.dakaqi.utils.encryption.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * Created by yangx
 * Date: 2016/7/20 0020
 * Time: 10:25
 */

@RestController
@RequestMapping(value = "/TestMaibao")
public class TestMaibaoController {

    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

    /**
     *
         {
         "nonce":"123456",
         "customerCode":"MIGfMA0GCS",
         "mobile":"15900948609",
         "activityName":"actibityTest111",
         "name":"yangx",
         "idCard":"610124198010220358",
         "startTime":"2026-07-12 10:08",
         "endTime":"2026-07-13 10:08",
         "key":"123456789"
         }
     *
     */

    @RequestMapping(value = "/getSign")
    public String test(HttpServletRequest request, HttpServletResponse response)throws Exception{

        String paramJsonString = parseRequestBody(request);
        Map<String, String> map = JSON.parseObject(paramJsonString, new TypeReference<Map<String, String>>() {
        });
        map = MapUtil.order(map);
        String key =  map.remove("key");
        String paramMap = MapUtil.mapJoin(map, false, false);
        paramMap = paramMap + "&key=" + key;
        String sign = DigestUtils.md5Hex(paramMap).toUpperCase();
        return  sign;
    }

    public String parseRequestBody(HttpServletRequest request) throws IOException {
        InputStream inputStream = request.getInputStream();
        return getRequestBodyJson(inputStream);
    }

    private String getRequestBodyJson(InputStream inputStream) throws IOException {
        Reader input = new InputStreamReader(inputStream, "UTF-8");
        Writer output = new StringWriter();
        char[] buffer = new char[DEFAULT_BUFFER_SIZE];
        int n;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toString();
    }

    @RequestMapping(value = "/test")
    @EncryptionParam
    public String test111(HttpServletRequest request, HttpServletResponse response)throws Exception{
        System.out.print("~~~~~~~调用成功~~~~~~~~");
        return  "调用成功！";
    }
}


